package de.kardass.jsmatep.util;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileWriter;
import java.io.IOException;
import java.io.Writer;

/**
 * Helper for writing text content into a file.
 * 
 * @author Manfred Kardass (manfred@kardass.de)
 * 
 */
public class ContentWriter {

    /**
     * Writes the content into the file. If the file does not exist, a new file
     * will be created.
     * 
     * @param file
     * @param contents
     * @throws FileNotFoundException
     * @throws IOException
     */
    public static void saveContents(String fileName, String contents) throws FileNotFoundException, IOException {
        final File file = new File(fileName);
        if (!file.exists()) {
            file.createNewFile();
        }
        saveContents(file, contents);
    }

    /**
     * Writes the content into the file.
     * 
     * @param file
     * @param contents
     * @throws FileNotFoundException
     * @throws IOException
     */
    public static void saveContents(File file, String contents) throws FileNotFoundException, IOException {
        if (file == null) {
            throw new IllegalArgumentException("File should not be null.");
        }
        if (!file.exists()) {
            throw new FileNotFoundException("File does not exist: " + file);
        }
        if (!file.isFile()) {
            throw new IllegalArgumentException("Should not be a directory: " + file);
        }
        if (!file.canWrite()) {
            throw new IllegalArgumentException("File cannot be written: " + file);
        }
        Writer output = new BufferedWriter(new FileWriter(file));
        try {
            output.write(contents);
        } finally {
            output.close();
        }
    }

}
